<?php

// Model:'CanBo' - Database Table: 'CanBo'

Class CanBo extends Eloquent {

    //Bang trong csdl
    private $nameTable = 'cb_tt';
    //Rang buoc du lieu
    private $rules = array(
        'mscb' => 'required|min:3|max:10',
        'hoten' => 'required|min:3|max:200'
    );
    //So can bo hien thi tren mot trang
    private $cbtt = 8;

    //Ham kiem tra du lieu
    public function validation($data) {
        return Validator::make($data, $this->rules);
    }

    //Lay so du lieu hien thi tren trang
    public function GetCBTT() {
        return $this->cbtt;
    }

    //Lay ds du lieu
    public function GetList($key) {
        $data = null;
        if ($key === null) {
            $data = DB::table($this->nameTable)
                    ->select("*")
                    ->orderBy("MSCB")
                    ->paginate($this->cbtt);
        } else {
            $data = DB::table($this->nameTable)
                    ->select("*")
                    ->where("MSCB", "LIKE", "%" . $key . "%")
                    ->orWhere("HO_TEN", "LIKE", "%" . $key . "%")
                    ->orderBy("MSCB")
                    ->paginate($this->cbtt);
        }

        return $data;
    }

    //Lay du lieu xac dinh
    public function GetOne($id) {
        return DB::table($this->nameTable)
                        ->select("*")
                        ->where("ID", $id)
                        ->first();
    }

    //
    public function GetWithMSCB($mscb) {
        return DB::table($this->nameTable)
                        ->select("*")
                        ->where("MSCB", $mscb)
                        ->first();
    }

    //Luu du lieu moi
    public function SaveIn($data) {
        $check = DB::table($this->nameTable)
                ->select("ID")
                ->where("MSCB", $data["MSCB"])
                ->first();
        if ($check == null) {
            return DB::table($this->nameTable)
                            ->insert($data);
        } else {
            return false;
        }
    }

    //Luu du lieu sua doi
    public function StoreIn($data, $id) {
        $check = DB::table($this->nameTable)
                ->select("*")
                ->where("MSCB", $data["MSCB"])
                ->where("ID", "<>", $id)
                ->first();
        if (!is_null($check)) {
            return false;
        } else {
            return DB::table($this->nameTable)
                            ->where("ID", $id)
                            ->update($data);
        }
    }

    //Xoa du lieu xac dinh
    public function Remove($id) {
        try {
            return DB::table($this->nameTable)
                            ->delete($id);
        } catch (Exception $ex) {
            return false;
        }
    }

}
